package com.wx.JerseySpring.filter;


import com.sun.jersey.core.reflection.MethodList;
import com.wx.JerseySpring.context.Context;
import com.wx.JerseySpring.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Administrator on 2016/11/17.
 */
public class IndexFilter implements HandlerInterceptor{

    public String[] allowUrls;

    public void setAllowUrls(String[] allowUrls){
        this.allowUrls = allowUrls;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        // 在这个拦截器里面配置一些字符编码为utf-8
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        // 首先静态资源不进行拦截
        String stringUri = request.getRequestURI().replace(request.getContextPath(),"");
        System.out.println(stringUri);
        if(allowUrls !=null&&allowUrls.length>1){
            for(String uri :allowUrls){
                if(stringUri.contains(uri)){
                    return true;
                }
            }
        }
        // 如果session超时，重新进行登录
        User user = (User) request.getSession().getAttribute(Context.CONTEXT_USER);
        if(user==null){
            response.sendRedirect("/index/index.html");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
